package com.fescoservice.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.fescoservice.exception.FSException;
import com.fescoservice.model.BBS;
import com.fescoservice.model.BBSContent;
import com.fescoservice.model.BBSId;
import com.fescoservice.model.Category;
import com.fescoservice.model.CategoryId;
import com.fescoservice.service.ContentService;

@Controller
@RequestMapping("/action/Content.htm")
public class ContentController {
	private static final Logger log = LogManager.getLogger(ContentController.class);

	@Autowired
	private ContentService contentService;

	@RequestMapping(params = "cmd=delete")
	public String listCategory(BBSId bbsId,ModelMap map, HttpServletRequest request) throws FSException {
		contentService.deleteContent(bbsId);
		getPreviewModel(map,bbsId);
		return "manage/bbspreview";
	}
	
	@RequestMapping(params = "cmd=addInit")
	public String addInit(CategoryId categoryId,ModelMap map,HttpServletRequest request) throws FSException{
		String lang =(String)request.getSession().getAttribute("userLanguage");
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode1());
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode2());
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode3());
		map.addAttribute("categoryId", categoryId);
		map.addAttribute("language", lang);
		return "manage/addbbsview";
	}
	
	@RequestMapping(params = "cmd=modifyInit")
	public String modifyInit(BBSId bbsId,ModelMap map,HttpServletRequest request) throws FSException{
		CategoryId categoryId= new CategoryId(bbsId.getBoardCode1(),bbsId.getBoardCode2(),bbsId.getBoardCode3());
		BBS viewBBS = contentService.findBBSById(bbsId);
		BBSContent viewBBSContent =contentService.findBBSContentById(bbsId);
		List attachments = contentService.findBBSAttachesById(bbsId);
		map.addAttribute("categoryId", categoryId);
		map.addAttribute("viewBBS", viewBBS);
		map.addAttribute("viewBBSContent", viewBBSContent);
		map.addAttribute("viewBBSAttaches", attachments);
		return "manage/addbbsview";
	}
	
	@RequestMapping(params = "cmd=setDefault")
	public String setDefault(BBSId bbsId,ModelMap map,HttpServletRequest request) throws FSException{
		contentService.setDefault(bbsId);
		getPreviewModel(map,bbsId);
		return "manage/bbspreview";
	}
	
	@RequestMapping(params = "cmd=view")
	public String viewDetail(BBSId bbsId,ModelMap map,HttpServletRequest request) throws FSException{
		getPreviewModel(map,bbsId);
		return "manage/bbspreview";
	}

	@RequestMapping(params = "cmd=add")
	public String addCategory(MultipartHttpServletRequest multipartRequest,BBSId bbsId, ModelMap map,
			HttpServletRequest request) throws FSException {
		List<MultipartFile> multipartFiles = new ArrayList();
		Iterator iter = multipartRequest.getFileNames();
		while (iter.hasNext()) {
			String fileName = (String) iter.next();
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName);
			multipartFiles.add(file);
		}
		String lang = (String) request.getSession().getAttribute("userLanguage");
		String title = (String)request.getParameter("title");
		String content = (String)request.getParameter("content");
		//String filecount = (String)request.getParameter("filecount");
		String charset = (String)request.getParameter("charset");
		String attachYn = (multipartFiles.size() > 0)?"Y":"N";
		String isEditor = (content.length()>0)?"Y":"N";
		String summary = (content.length()>400)?content.substring(0,400):content;
		log.debug("~~~~~~~~Controller begin addCategory~~~~~~~~" + lang);

        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
		String webUrl=request.getSession().getServletContext().getRealPath("/"); 
		File filePath = new File(webUrl+"uploadDir"+ File.separator + df1.format((new Date()).getTime()));    
        if (!filePath.exists()) {   
            filePath.mkdirs();   
        }   	
       
		Long seq = contentService.countBBSId(bbsId);
		bbsId.setBoardSeq(++seq);
		
		BBS bbs = new BBS(bbsId, "N", title, new Date(), new Date(), 1L,0L,0L,0L,0L,
				attachYn, isEditor,lang, charset, summary, "N", "N");	
		BBSContent bbscontent = new BBSContent(bbsId, content,"");
		contentService.addContent(bbsId,bbs,bbscontent,multipartFiles,filePath);
		getPreviewModel(map,bbsId);
		return "manage/bbspreview";
	}
	
	@RequestMapping(params = "cmd=modify")
	public String modifyCategory(MultipartHttpServletRequest multipartRequest,BBSId bbsId, ModelMap map,
			HttpServletRequest request) throws FSException {
		List<MultipartFile> multipartFiles = new ArrayList();
		Iterator iter = multipartRequest.getFileNames();
		while (iter.hasNext()) {
			String fileName = (String) iter.next();
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName);
			multipartFiles.add(file);
		}
		String lang = (String) request.getSession().getAttribute("userLanguage");
		String title = (String)request.getParameter("title");
		String content = (String)request.getParameter("content");
		String charset = (String)request.getParameter("charset");
		String attachYn = (multipartFiles.size() > 0)?"Y":"N";
		String isEditor = (content.length()>0)?"Y":"N";
		String summary = (content.length()>400)?content.substring(0,400):content;

		BBS bbs = contentService.findBBSById(bbsId);	
		BBSContent bbscontent = contentService.findBBSContentById(bbsId);
		bbs.setTitle(title);
		bbs.setUpdateDate(new Date());
		bbs.setAttachYn(attachYn);
		bbs.setIsEditor(isEditor);
		bbs.setSummary(summary);
		bbscontent.setContent(content);
		
		
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
		String webUrl=request.getSession().getServletContext().getRealPath("/"); 
		File filePath = new File(webUrl+"uploadDir"+ File.separator + df1.format((new Date()).getTime()));    
        if (!filePath.exists()) {   
            filePath.mkdirs();   
        }   	
		
		contentService.updateContent(bbs,bbscontent,multipartFiles,filePath);
		getPreviewModel(map,bbsId);
		return "manage/bbspreview";
	}
	
	private ModelMap getPreviewModel(ModelMap map, BBSId bbsId) throws FSException{	
		CategoryId categoryId= new CategoryId(bbsId.getBoardCode1(),bbsId.getBoardCode2(),bbsId.getBoardCode3());
		List bbslist = contentService.findBBSByCategory(categoryId);
		BBS viewBBS = contentService.findBBSById(bbsId);
		BBSContent viewBBSContent =contentService.findBBSContentById(bbsId);
		List attachments = contentService.findBBSAttachesById(bbsId);
		
		map.addAttribute("categoryId", categoryId);
		map.addAttribute("bbslist", bbslist);
		map.addAttribute("viewBBS", viewBBS);
		map.addAttribute("viewBBSContent", viewBBSContent);
		map.addAttribute("viewBBSAttaches", attachments);
		return map;
	}
}